# -*- coding: utf-8 -*-
from api import api, GlobalError
from bson import ObjectId
from config import OSS_VIDEO_BUCKET, OSS_APP_ID, OSS_APP_KEY, OSS_HOST, \
    OSS_INTERNAL_HOST, OSS_URL_TIME_OUT
from flask import jsonify, request
from lib.oss.oss_api import OssAPI
from model.studio import Studio
from model.user import User
from model.video import Video
from util.oss_helper import oss_url_upload
from time import time


@api.route('/video-url', methods=['POST'])
def get_video_upload_url():
    '''
## 获取上传视频的 Url

    POST /api/video-url

Parameters:

* `suffix` (required) - 视频后缀
* `contentType` (required) - content type

Return:

* `url` (string) - Url to upload video

Errors: `4`
    '''
    suffix = request.form.get('suffix', '')
    content_type = request.form.get('contentType', None)
    if suffix not in ['mp4']:
        return jsonify(stat=0, **GlobalError.REFUSED_FILE_FORMAT), 403
    filename = '.'.join([str(ObjectId()) + str(int(time())), suffix])
    sign_url = oss_url_upload(OSS_VIDEO_BUCKET, filename, OSS_URL_TIME_OUT, content_type)
    print sign_url

    return jsonify(stat=1, url=sign_url)


@api.route('/video/video', methods=['POST'])
def upload_video():
    '''
## 上传视频

    POST /api/video/video

Parameters:

* `video` (文件, required)

Return:

* `url` (string) - Url of video

Errors: `4`
    '''
    video_file = request.files['video']
    suffix = video_file.filename.split('.')[-1]
    if suffix not in ['mp4']:
        return jsonify(stat=0, **GlobalError.REFUSED_FILE_FORMAT), 403

    filename = '.'.join([str(ObjectId()) + str(int(time())), suffix])
    oss = OssAPI(OSS_INTERNAL_HOST, OSS_APP_ID, OSS_APP_KEY)
    oss.put_object_from_string(OSS_VIDEO_BUCKET, filename, video_file.stream.read())

    url = 'http://' + OSS_VIDEO_BUCKET + '.' + OSS_HOST + '/' + filename

    return jsonify(stat=1, url=url)


@api.route('/video', methods=['POST'])
def new_video():
    '''
## 创建新视频

    POST /api/video

Parameters:

* `title` (optional) - 视频标题
* `description` (optional) - 视频描述
* `imageUrl` (optional)
* `userId` (optional) - 视频所属老师ID
* `studioId` (required) - 视频所属画室 ID
* `videoUrl` (required) - 视频链接

Return:

* `videoId`
    '''
    title = request.form.get('title', '')
    image_url = request.form.get('imageUrl', '')
    description = request.form.get('description', '')
    userId = request.form.get('userId', '')
    studioId = request.form.get('studioId', None)
    videoUrl = request.form.get('videoUrl', None)

    if studioId is None or videoUrl is None:
        return jsonify(stat=0, **GlobalError.PARAMETERS_INVALID), 403

    video_id = Video.new_video(title, description, image_url, userId, studioId, videoUrl)
    return jsonify(stat=0, videoId=video_id)


@api.route('/video/<video_id>', methods=['GET'])
def get_video_info(video_id):
    '''
## 获取视频详细信息

    GET /api/video/<video_id>

Return:

* `_id` (string) - 视频的 ID
* `createTime` (long) - 视频创建时间
* `title` (string) - 视频标题
* `description` (string) - 视频描述
* `imageUrl` (string)
* `updateTime` (long) - 视频最近一次更新时间
* `userId` (string) - 视频归属的老师的 ID，可为空
* `name` (string) - 视频归属老师名字
* `avatarUrl` (string) - 视频归属老师头像链接
* `studioId` (string) - 视频归属的画室的 ID
* `videoUrl` (string) - 视频的链接
* `verified` (int) - 视频是否通过审核
    '''
    try:
        video = Video.get({
            Video.Field._id: video_id
        })
    except:
        return jsonify(stat=0, **GlobalError.INVALID_VIDEO_ID), 403
    try:
        user = User.get({
            User.Field._id: video.data.get(Video.Field.userId)
        }, [
            User.Field.name,
            User.Field.avatarUrl
        ])
        video.data[User.Field.name] = user.data.get(User.Field.name)
        video.data[User.Field.avatarUrl] = user.data.get(User.Field.avatarUrl)
    except:
        video.data[User.Field.name] = ""
        video.data[User.Field.avatarUrl] = ""
        pass

    return jsonify(stat=1, video=video.data)


@api.route('/video/<video_id>', methods=['PUT'])
def update_video_info(video_id):
    '''
## 更新视频详细信息

    PUT /api/video/<video_id>

Parameters:

* `title` (string, optional)
* `description` (string, optional)
* `imageUrl` (string, optional)
* `videoUrl` (string, optional)
* `userId` (string, optional)
    '''
    try:
        video = Video.get({
            Video.Field._id: video_id
        })
    except:
        return jsonify(stat=0, **GlobalError.INVALID_VIDEO_ID), 403

    update_info = {}
    update_info['$set'] = {}

    title = request.form.get('title', None)
    if title is not None:
        update_info['$set'][Video.Field.title] = title

    description = request.form.get('description', None)
    if description is not None:
        update_info['$set'][Video.Field.description] = description

    image_url = request.form.get('imageUrl', None)
    if image_url is not None:
        update_info['$set'][Video.Field.imageUrl] = image_url

    video_url = request.form.get('videoUrl', None)
    if video_url is not None and video_url:
        update_info['$set'][Video.Field.videoUrl] = video_url

    user_id = request.form.get('userId', None)
    if user_id is not None:
        update_info['$set'][Video.Field.userId] = user_id

    video.update({
        '$set': update_info
    })
    return jsonify(stat=1)


@api.route('/video/<video_id>', methods=['DELETE'])
def delete_video(video_id):
    '''
## 删除视频

    DELETE /api/video/<video_id>
    '''
    try:
        video = Video.get({
            Video.Field._id: video_id
        })
    except:
        return jsonify(stat=0, **GlobalError.INVALID_VIDEO_ID), 403

    try:
        studio = Studio.get({
            Studio.Field._id: video.data.get(Video.Field.studioId)
        })
        studio.update({
            '#pull': {
                Studio.Field.video: video_id
            }
        })
    except:
        pass
    Video.remove({
        Video.Field._id: video_id
    })
    return jsonify(stat=1)
